<?php

namespace app\service;

use app\common\model\ChangguanYuyue;
use app\service\LogService;
use EasyWeChat\Factory;
use app\service\OrderService;
use app\common\model\Order as OrderModel;
use app\common\model\ChatMoney as ChatMoneyModel;
use app\common\model\User as UserModel;
use app\common\model\ChatMsg as ChatMsgModel;
use app\common\model\Loginstatus;
use app\common\model\VideoPay as VideoPayModel;
use app\common\model\OrderShoufei;
use app\common\model\OrderGoodsclasses;


use EasyWeChat\Kernel\Messages\NewsItem;


class PayService extends BaseService
{
    public static $payment;

    public function __construct()
    {
        $config = [
            //'app_id' => config('authorizer_appid'),
            'app_id' => config('xiaochengxu_appid'),
            'mch_id' => config('wechat_mchid'),
            'key' => config('wechat_mchkey'),
            //'notify_url'         => request()->domain()."/notify/wechat/mall_id/".$this->mall_id,
            'cert_path' => config('wechat_mchcertpem'),
            'key_path' => config('wechat_mchkeypem'),
        ];
        self::$payment = Factory::payment($config);
    }


    /* 微信支付退款 */
    public function wechatRefund($orderInfo, $refund_no = false)
    {
        if (!$refund_no) {
            $refund_no = $orderInfo['order_sn'] . rand(0,9);
        }

        $money = (int)($orderInfo['pay_money'] * 100);


        $result = self::$payment->refund->byOutTradeNumber($orderInfo['order_sn'], $refund_no, $money, $money, [
            'refund_desc' => '订单退款',
//            'notify_url' => request()->domain() . "/notify/yudingrefund",
        ]);


//        dump($money);die;
        LogService::S()->writeLog("data", 'wechatRefund', $result);
        if ($result['return_code'] == 'SUCCESS' && $result['return_msg'] == 'OK') {
            return true;
        }
        return json_encode($result);
    }


    /* 企业付款 */
    public function qiyePay($log, $userInfo)
    {
        $result = self::$payment->transfer->toBalance([
            'partner_trade_no' => 'qiyepay' . $log['id'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            //'openid' => UserModel::uid2openid($log['uid']),
            'openid' => $userInfo['openid_main'],
            'check_name' => 'FORCE_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => $log['bank_card_name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $log['atm_money'] * 100, // 企业付款金额，单位为分
            'desc' => '社群资金提现', // 企业付款操作说明信息。必填
        ]);
        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            return true;
        }
        return $result['err_code_des'];
    }

    /* 获取支付sdk */
    public function wechatJssdk($config)
    {
        $config['total_fee'] = (int)$config['total_fee'];
        $result = self::$payment->order->unify($config);
        $jsapi = self::$payment->jssdk->sdkConfig($result['prepay_id']);
        return $jsapi;
    }

    /* 微信发红包支付成功 */
    public function YudingPaySuccess()
    {

        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            // LogService::S()->writeLog('WechatPayLog','',$message);
            $moneyLog = ChangguanYuyue::getOne([
                'order_sn' => $message['out_trade_no']
            ]);
            if (!$moneyLog || $moneyLog['checked'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    ChangguanYuyue::where('order_sn', $message['out_trade_no'])->update(
                        ['checked' => 1]
                    );

                } else {
                    LogService::S()->writeLog('$fail', 'filed', '通信失败,请稍后再通知我');
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();
    }

    public function YudingRefundSuccess()
    {

        $response = self::$payment->handleRefundedNotify(function ($message, $fail) {
            // LogService::S()->writeLog('WechatPayLog','',$message);
            $moneyLog = ChangguanYuyue::getOne([
                'order_sn' => $message['out_trade_no']
            ]);
            if (!$moneyLog || $moneyLog['checked'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    ChangguanYuyue::where('order_sn', $message['out_trade_no'])->update(
                        ['checked' => 3]
                    );

                } else {
                    LogService::S()->writeLog('$fail', 'filed', '通信失败,请稍后再通知我');
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();
    }

    /* 支付成功回调 */
    public function wechatPaySuccess()
    {
        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            LogService::S()->writeLog('WechatPayLog', '', $message);
            $order = OrderModel::getOne([
                'order_sn' => $message['out_trade_no']
            ]);
            if (!$order || $order['checked'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    OrderService::S()->changeOrder($order, [
                        'checked' => 1,
                        'pay_time' => time(),
                    ]);
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();
    }

    /* 支付成功回调 */
    public function shoufeiPaySuccess()
    {
        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            LogService::S()->writeLog('ShoufeiWechatPayLog', '', $message);
            $order = OrderShoufei::getOne([
                'order_sn' => array('=',$message['out_trade_no'])
            ]);
            if (!$order || $order['checked'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    OrderShoufei::update([
                        'checked' => 1,
                        'pay_time' => time(),
                    ], [
                        'order_sn' => $message['out_trade_no']
                    ]);
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();

    }

    /* 支付成功回调 */
    public function goodsclassesPaySuccess()
    {
        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            LogService::S()->writeLog('GoodsclassesWechatPayLog', '', $message);
            $order = OrderGoodsclasses::getOne([
                'order_sn' => array('=',$message['out_trade_no'])
            ]);
            if (!$order || $order['checked'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    OrderGoodsclasses::update([
                        'checked' => 1,
                        'pay_time' => time(),
                    ], [
                        'order_sn' => $message['out_trade_no']
                    ]);
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();

    }

    public function wechatVideoSuccess()
    {
        $response = self::$payment->handlePaidNotify(function ($message, $fail) {
            LogService::S()->writeLog('WechatPayLog', '', $message);
            $order = VideoPayModel::getOne([
                'order_sn' => $message['out_trade_no']
            ]);
            if (!$order || $order['status'] != 0) {
                return true;
            }
            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                if ($message['result_code'] === 'SUCCESS') {
                    VideoPayModel::where([
                        'id' => $order['id']
                    ])->update([
                        'status' => 1
                    ]);
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
        });
        return $response->send();
    }

}